﻿/**************************************************************************
创建日期:	2019/5/12 21:42:29     
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com
创建时间:	
Copyright (c)    ZhCun.cn

描	述：
记	录：
***************************************************************************/
using System;
using System.Reflection;
using ZhCun.DbCore.BuildSQLText;
using ZhCun.DbCore.Cores;
using ZhCun.DbCore.Example.DbModels;

namespace ZhCun.DbCore.Example
{
    class DBContext01 : DBContextBase
    {
        Guid _loginUserId;

        public void SetLoginUserId(Guid loginUserId)
        {
            _loginUserId = loginUserId;
        }

        /// <summary>
        /// 根据属性名设置对象的属性值
        /// </summary>
        public static void SetPropertyValue<T>(T obj, string pName, object pValue) where T : class, new()
        {
            Type t = typeof(T);
            PropertyInfo pInfo = t.GetProperty(pName, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);

            if (pInfo != null && pInfo.CanWrite)
            {
                if (pValue == null || DBNull.Value.Equals(pValue) || Guid.Empty.Equals(pValue))
                {
                    return;
                }
                string pTypeName = pInfo.PropertyType.Name.ToUpper();
                if (pTypeName == "GUID")
                {
                    pValue = new Guid(pValue.ToString());
                }
                else
                {
                    pValue = Convert.ChangeType(pValue, pInfo.PropertyType);
                }
                pInfo.SetValue(obj, pValue, null);
            }
        }
        /// <summary>
        /// 结果完成的处理方法，如：写入日志
        /// </summary>
        protected override void ResultFinish(BaseResult result)
        {
            //Task.Factory.StartNew(() => { });
            var sql = result.SqlContent;
            Console.WriteLine("执行标记:{0}", result.ResultMark);
            Console.WriteLine("SQL：{0}", sql);
            Console.WriteLine("耗时：{0}", result.ExecInterval);
            Console.WriteLine("所影响行：{0}", result.RowCount);
            Console.WriteLine();
        }
        public override ExecResult Insert<TEntity>(TEntity entity)
        {
            //如果该实体有“UserId”字段那么缺省赋值为：_loginUserId 值
            SetPropertyValue(entity, "UserId", _loginUserId);
            //如果字段Id没有被赋值，则赋值默认字段为新的Guid
            if (!entity.IsChangeField("Id"))
            {
                SetPropertyValue(entity, "Id", Guid.NewGuid());
            }
            //如果实体有“CreateTime” 字段，设置为当前时间
            SetPropertyValue(entity, "CreateTime", DateTime.Now);
            return base.Insert<TEntity>(entity);
        }
        protected override ExecResult UpdateBase<TEntity>(TEntity entity, Func<ISqlBuilder, string> whereFun)
        {
            SetPropertyValue(entity, "ModifyTime", DateTime.Now);
            return base.UpdateBase<TEntity>(entity, whereFun);
        }
        protected override void BeforeExecSqlBuilder<TEntity>(ISqlBuilder sqlBuilder, EmDbOperation opType)
        {
            //user 没有UserId 字段加上过滤
            if (typeof(TEntity) == typeof(TUser))
            {
                return;
            }
            //判断当前执行方法是否指定了过滤条件
            if (QueryFilterHelper.IsFilter())
            {
                //追加sql文本，同时会把所有已有条件加上括号，并加上and符号
                sqlBuilder.AddSqlTextByGroup(" UserId = {0}", sqlBuilder.AddParam(_loginUserId));
            }
        }
    }
}